package com.nj9you.pay.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.nj9you.pay.utils.Constants;
import com.nj9you.pay.utils.Utils;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

public class WxPayActivity extends Activity {

    private String orderId;
    private String price;
    private String subject;
    private String body;
    private String gameName;
    private String pkgname;
    private String attach;
    private String callbak;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Intent.ACTION_MAIN.equals(getIntent().getAction())) {
            finish();
            return;
        }
        getIntentData();
        if (wechatNotInstall()) {
            Utils.sendPayResult(this, -2, Utils.getString(this, "wx_not_installed"));
            finish();
            return;
        }
        pay();
        finish();
    }

    private boolean wechatNotInstall() {
        IWXAPI api = WXAPIFactory
                .createWXAPI(this, Constants.APP_ID);
        return !api.isWXAppInstalled();
    }

    private void getIntentData() {
        orderId = getIntent().getStringExtra("order");
        price = getIntent().getStringExtra("price");
        subject = getIntent().getStringExtra("subject");
        body = getIntent().getStringExtra("body");
        gameName = getIntent().getStringExtra("game");
        attach = getIntent().getStringExtra("attach");
        pkgname = getIntent().getStringExtra("package");
        callbak = getIntent().getStringExtra("callback");
        Utils.setCallback(callbak);
    }

    private void pay() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", Constants.APP_ID);

        params.put("mch_id", Constants.PARTNER_ID);

        params.put("nonce_str", Utils.getRandom32());

        /**
         * 商品描述交易字段格式根据不同的应用场景按照以下格式：
         * APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
         */
        params.put("body", subject);

        /**
         * 透传参数
         */
        params.put("attach", attach);

        params.put("out_trade_no", orderId); // 商户订单号

        params.put("total_fee", String.valueOf(price));

        params.put("spbill_create_ip", Utils.getLocalIpAddress());

        params.put("notify_url", Constants.NOTIFY_URL);

        params.put("trade_type", "APP");

        Utils.wxgfPay(this, params);
    }
}
